package com.rockbb.common.simpleframe.action;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.rockbb.common.simpleframe.result.ActionResult;
import com.rockbb.common.simpleframe.result.ResultHandler;
import com.rockbb.common.utilities.ObjectUtils;

public class ActionContainer 
{
	private static Logger logger = Logger.getLogger(ActionContainer.class);
	private ActionContext context;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<String, Object> root;

	public ActionContainer(ActionContext cxt, HttpServletRequest req, HttpServletResponse res)
	{
		context = cxt;
		request = req;
		response = res;
		root = new HashMap<String, Object>();
	}

	public void process() 
	{
		String resultName = "";

		ActionSupport action = (ActionSupport)ObjectUtils.getClassInstanceByName(context.getActionClassName());
		if (action == null) 
		{
			resultName = ActionSupport.ERROR;
		}
		else
		{
			try 
			{
				action.initialize(context, request, response, root);
				action.prepare();
				resultName = action.intercepters();
				if (resultName == null || resultName.equals(ActionSupport.SUCCESS))
				{
					logger.debug("action:"+context.getActionClassName()+", method:"+context.getActionMethodName());
					Method method = action.getClass().getMethod(context.getActionMethodName());
					resultName = (String) method.invoke(action);
				}
			}
			catch (NoSuchMethodException e) 
			{
				resultName = ActionSupport.ERROR;
				logger.info("NoSuchMethodException");
				logger.debug("Exception details:", e);
			}
			catch (IllegalAccessException e) 
			{
				resultName = ActionSupport.ERROR;
				logger.info("IllegalAccessException");
				logger.debug("Exception details:", e);
			} 
			catch (InvocationTargetException e) 
			{
				resultName = ActionSupport.ERROR;
				logger.info("InvocationTargetException");
				logger.debug("Exception details:", e);
			} 
			catch (Exception e) 
			{
				resultName = ActionSupport.ERROR;
				logger.info("Unknown Exception");
				logger.debug("Exception details:", e);
			}
		}

		try
		{
			ActionResult result = context.getResults().get(resultName);
			if (result != null) 
			{
				ResultHandler resultHandler = new ResultHandler(request, response);
				logger.debug("process result name:"+result.getName()+", type:"+result.getType()+", value: "+result.getValue());
				resultHandler.process(result, root);
			}
		}
		catch (Exception e)
		{
			logger.info("Unknown Exception");
			logger.debug("Exception details:", e);
		}
	}

}
